<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Services\AdminManager;
use App\Http\Services\CommonManager;
use App\Http\Services\UserManager;
use App\Permission;
use App\Role;
use App\User;
use Blocktrail\CryptoJSAES\CryptoJSAES;
use http\Env\Response;
use Illuminate\Contracts\Auth\Guard;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Cookie;
use Hash;
use Illuminate\Support\Facades\DB;

class AuthController extends Controller
{
    /**
     * 后台登录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function signInUser(Request $request){
        $username = $request->get('username');
        $password = $request->get('password');

        /** @var User $isUser */
        $isUser = User::whereUsername(trim($username))->first();
        if(!$isUser)
            return response()->json(['level' => 'error','message' => '该用户不存在']);

        /** @var User $user */
        $user = UserManager::signInByUsername($username,$password,0);
        if(!$user)
            return response()->json(['level'=>'error','message'=>'帐号或密码错误！']);

        if($user->role != 1)
            return response()->json(['level' => 'error','message' => '该用户无法登陆']);

        $systemAdmin = Role::whereName('system_admin')->first();
        if($systemAdmin){
            $systemAdminExists = DB::table('role_user')->where('user_id',$user->id)->where('role_id',$systemAdmin->id)->first();
        }else{
            $systemAdminExists = null;
        }

        if(!$user->can('admin_sign_in') && !$systemAdminExists)
            return response()->json(['level' => 'error','message' => '没有登录权限','data'=>'no_permission']);

        if($user->status != 1)
            return response()->json(['level' => 'error','message' => '该账号已被锁定']);

        $userMark = $user->user_key;

        $token = CryptoJSAES::encrypt($userMark,env('AES_KEY'));

        $cookie = Cookie::forever("admin_token", $token);

        return response()->json(['level' => 'success','message' => trans("登录成功！"),'data' => $token])->withCookie($cookie);
    }

    /**
     * 修改密码
     * @param Guard $guard
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function changePassword(Guard $guard,Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $oldPassword = $request->get('oldpassword');
        $newpassword = $request->get('newpassword');
        $repass   = $request->get('repass');

        if(is_null($oldPassword) && $oldPassword == '')
            return response()->json(['level' => 'error','message' => '请输入原密码']);

        if(is_null($newpassword) && $newpassword == '')
            return response()->json(['level' => 'error','message' => '请输入新密码']);

        if(is_null($repass) && $repass == '')
            return response()->json(['level' => 'error','message' => '请再次输入新密码']);

        if(!Hash::check($oldPassword,$adminUser->password))
            return response()->json(['level'=>'error','message'=>'原密码不匹配！']);

        if(Hash::check($newpassword,$adminUser->password))
            return response()->json(['level'=>'error','message'=>'原密码与新密码不能一致！']);

        if($newpassword != $repass)
            return response()->json(['level'=>'error','message' => '两次密码不一致！嘛']);

        $adminUser->password = bcrypt($newpassword);
        $adminUser->save();

        $loginOut = Cookie::forget('admin_token');

        return response()->json(['level'=>'success','message'=>trans("密码修改成功！"),'data' => 'no_login'])->withCookie($loginOut);
    }

    /**
     * 退出登录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function loginOut(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $cookie = Cookie::forget('admin_token');

        return response()->json(['level' => 'success','message' => '退出成功','data' => 'no_login'])->withCookie($cookie);
    }

    /**
     * 获取管理员信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getAdminUserInfo(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        return response()->json(['level' => 'success','message' => '获取成功','data' => $adminUser]);
    }


    /**
     * 获取管理员列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function adminList(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page    = !is_null($request->get('page')) ? $request->get('page') : 1;
        $limit   = !is_null($request->get('limit')) ? $request->get('limit') : 16;

        $arr = [
            'page' => $page,
            'limit' => $limit,
        ];

        $adminUserList = User::whereRole(1);

        $arr['total'] = $adminUserList->count();

        if($adminUser->hasRole("virtual_admin")){
            $adminUserList = $adminUserList->whereIn("id",[$adminUser->id])->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();
        }else{
            $adminUserList = $adminUserList->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();
        }

        if(count($adminUserList) > 0){
            foreach($adminUserList as $adminUser){
                $UserRole = DB::table('role_user')->where('user_id',$adminUser->id)->first();
                if($UserRole){
                    /** @var Role $role */
                    $role = Role::whereId($UserRole->role_id)->first();
                    if($role){
                        $adminUser->role_name = $role->display_name;
                    }else{
                        $adminUser->role_name = null;
                    }
                }else{
                    $adminUser->role_name = null;
                }

                if($adminUser->status == 1){
                    $adminUser->status_name = '开启';
                }else{
                    $adminUser->status_name = '关闭';
                }
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $adminUserList,'page_info' => $arr]);
    }

    /**
     * 管理员信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function adminSet(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $thisAdminUser = User::whereRole(1)->whereId($id)->first();
        if($thisAdminUser){
            $roleUsers = DB::table('role_user')->where('user_id',$thisAdminUser->id)->get();
            $roleIds = array();
            if(count($roleUsers) > 0){
                foreach($roleUsers as $roleUser){
                    /** @var Role $role */
                    $roleList = Role::whereId($roleUser->role_id)->get();
                    if(count($roleList) > 0){
                        foreach($roleList as $role){
                            $roleObj = $role->id;
                            array_push($roleIds,$roleObj);
                        }
                    }

                }
            }

            $thisAdminUser->role_id = $roleIds;
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $thisAdminUser,'id' => $id]);
    }

    public function getMyPermission(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $userPermissionIds = DB::table("users")
            ->leftJoin('role_user', 'users.id', '=', 'role_user.user_id')
            ->leftJoin("permission_role","role_user.role_id",'=','permission_role.role_id')
            ->whereNull("users.deleted_at")
            ->where("users.id","=",$adminUser->id)
            ->pluck("permission_role.permission_id");

        $permissions = Permission::whereIn("id",$userPermissionIds)->get();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $permissions]);
    }

    /**
     * 添加管理员用户
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setAdmin(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $username   = $request->get('username');
        $password   = $request->get('password');
        $roleIds    = $request->get('role_id');
        $adminName  = $request->get('admin_name');
        $phone      = $request->get('phone');
//        $repass   = $request->get('repass');
        $status     = !is_null($request->get('status')) && $request->get('status') != '' ? $request->get('status') : 0;
        $id         = !is_null($request->get('id')) ? $request->get('id') : 0;

        if(!is_array($roleIds) || (is_array($roleIds) && count($roleIds) <= 0))
            return response()->json(['level' => 'error','message' => '角色的数据格式不对']);

        /** @var User $hasUser */
        $hasUser = User::whereUsername(trim($username))->first();

        /** @var User $thatUser */
        $thatUser = User::whereId($id)->first();

        if($thatUser && ($hasUser && $thatUser->id != $hasUser->id))
            return response()->json(['level' => 'error','message' => '当前管理员账号已存在']);

        if($phone != '' && !is_null($phone)){
            $phoneVerification = CommonManager::phoneVerification(trim($phone));
            if(!$phoneVerification)
                return response()->json(['level' => 'error','message' => '手机号格式不正确']);

            $isPhone = User::wherePhone(trim($phone))->whereRole(1)->first();

            if($thatUser && ($isPhone && $thatUser->id != $isPhone->id))
                return response()->json(['level' => 'error','message' => '当前手机号已被使用']);
        }

        if(!$thatUser){
            if($hasUser)
                return response()->json(['level'=>'error','message' => '当前管理员账号已存在']);

            if($phone != '' && !is_null($phone)) {
                if ($isPhone)
                    return response()->json(['level' => 'error', 'message' => '当前手机号已被使用']);
            }
//            if(is_null($repass) && $repass == '')
//                return response()->json(['level' => 'error','message' => '请再次输入密码']);
//
//            if($password != $repass)
//                return response()->json(['level'=>'error','message' => '两次密码不一致！']);

            $thatUser = new User();
            $thatUser->user_key = md5($password . rand(1000,9999).time());
        }

        $thatUser->username    = $username;
        $thatUser->phone       = $phone;
        $thatUser->admin_name  = $adminName;

        if(!empty($password))
            $thatUser->password    = bcrypt($password);

        $thatUser->role        = 1;
        $thatUser->reg_ip      = $request->ip();
        $thatUser->reg_time    = date("Y-m-d H:i:s",time());
        $thatUser->status      = $status;
        $thatUser->save();

        DB::table('role_user')->where('user_id',$thatUser->id)->delete();

        foreach($roleIds as $roleId){
            $role = Role::whereId($roleId)->first();
            if($role){
                DB::table('role_user')->insert(['user_id' => $thatUser->id,'role_id' => $roleId]);
            }
        }

        return response()->json(['level'=>'success','message'=>'添加成功','data'=>$thatUser]);
    }

    /**
     * 改变管理员状态
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function changeAdminStatus(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        /** @var User $thatUser */
        $thatUser = User::whereId($id)->whereRole(1)->first();
        if(!$thatUser)
            return response()->json(['level' => 'success','message' => '管理员不存在']);

        if($thatUser->status == 1){
            $thatUser->status = 0;
        }else{
            $thatUser->status = 1;
        }

        $thatUser->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $thatUser]);
    }

    /**
     * 删除管理员用户
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delAdmin(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = !is_null($request->get('id'))?$request->get('id'):0;

        /** @var User $thatUser */
        $thatUser = User::whereId($id)->whereRole(1)->first();
        if(!$thatUser)
            return response()->json(["level"=>"error","message"=>"该管理员不存在！"]);

        if($thatUser->id == 1)
            return response()->json(['level' => 'error','message' => '该管理员无法删除']);

        $thatUser->delete();

        return response()->json(["level"=>"success","message"=>"删除成功","data"=>$thatUser]);
    }

    /**
     * 获取角色列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function roleList(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page    = !is_null($request->get('page')) ? $request->get('page') : 1;
        $limit   = !is_null($request->get('limit')) ? $request->get('limit') : 16;

        $arr = [
            'page' => $page,
            'limit' => $limit,
        ];

        $roles = Role::whereType('admin');

        $arr['total'] = $roles->count();

        $roles = $roles->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $roles,'page_info' => $arr]);
    }

    /**
     * 角色信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function roleSet(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        /** @var Role $role */
        $role = Role::whereId($id)->first();
        if($role){
            $permissionRoles = DB::table('permission_role')->where('role_id',$role->id)->get();
            $permissionIds = array();
            if(count($permissionRoles) > 0){
                foreach($permissionRoles as $permissionRole){
                    /** @var Permission $permission */
                    $permissionList = Permission::whereId($permissionRole->permission_id)->get();
                    if(count($permissionList) > 0){
                        foreach($permissionList as $permission){
                            $permissionObj = $permission->id;
                            array_push($permissionIds,$permissionObj);
                        }
                    }

                }
            }

            $role->permission_id = $permissionIds;
        }

        /** @var Permission $permission */
        $permissions = Permission::whereType('admin')->get();
        $permissionArr = array();
        if(count($permissions) > 0){
            foreach($permissions as $permission){
                $permissionInfo = (object)['id' => $permission->id,'permission' => $permission->display_name];
                array_push($permissionArr,$permissionInfo);
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $role,'permission_list' => $permissionArr]);
    }

    /**
     * 添加角色
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setRole(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $name          = $request->get('name') ?? '';
        $displayName   = $request->get('display_name');
        $description   = $request->get('description');
        $id            = !is_null($request->get('id')) ? $request->get('id') : 0;
        $permissionIds = $request->get('permission_id');

        if(empty($displayName))
            return response()->json(['level' => 'error','message' => '请输入角色名']);

        $isName = Role::whereType('admin')->whereDisplayName($displayName)->first();
        if($isName)
            return response()->json(['level' => 'error','message' => '该角色名已存在']);

        $newRole = Role::whereId($id)->first();

        if($isName && ($newRole && $isName->id != $newRole->id))
            return response()->json(['level' => 'error','message' => '该角色名已存在']);

        if(!$newRole){
            if($isName)
                return response()->json(['level' => 'error','message' => '该角色名已存在']);

            $newRole = new Role();
        }

        $newRole->name = $name;
        if(!is_null($displayName))$newRole->display_name = $displayName;
        if(!is_null($description))$newRole->description = $description;
        $newRole->type                                   = 'admin';
        $newRole->save();

        DB::table('permission_role')->where('role_id',$newRole->id)->delete();

        if(is_array($permissionIds)){
            if(count($permissionIds) > 0){
                foreach($permissionIds as $permissionId){
                    DB::table('permission_role')->insert(['role_id' => $newRole->id,'permission_id' => $permissionId]);
                }
            }
        }else{
            return response()->json(['level' => 'error','message' => '权限的数据格式不对']);
        }

        return response()->json(['level' => 'success','message' => '设置成功']);
    }

    /**
     * 删除角色
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delRole(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $thisRole = Role::whereId($id)->first();
        if(!$thisRole)
            return response()->json(['level' => 'error','message' => '该角色不存在']);

        $thisRole = DB::table('roles')->where('id',$id)->delete();

        return response()->json(['level' => 'success','message' => '删除成功','data' => $thisRole]);
    }

    /**
     * 获取权限列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function permissionsList(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $page    = !is_null($request->get('page')) ? $request->get('page') : 1;
        $limit   = !is_null($request->get('limit')) ? $request->get('limit') : 16;

        $arr = [
            'page' => $page,
            'limit' => $limit,
        ];

        $permissions = Permission::whereType('admin');

        $arr['total'] = $permissions->count();

        $permissions = $permissions->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $permissions,'page_info' => $arr]);
    }

    /**
     * 编辑权限
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function permissionsSet(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

//        $id = !is_null($request->get('id')) ? $request->get('id') : 0;
        $id = $request->get('id');


        $permission = Permission::whereId($id)->first();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $permission,'id' => $id]);
    }

    /**
     * 添加权限
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setPermissions(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $name          = $request->get('name');
        $displayName   = $request->get('display_name');
        $description   = $request->get('description');
        $id            = !is_null($request->get('id')) ? $request->get('id') : 0;

        $newPermission = Permission::whereId($id)->first();
        if(!$newPermission)
            $newPermission = new Permission();

        if(!is_null($name))$newPermission->name = $name;
        if(!is_null($displayName))$newPermission->display_name = $displayName;
        if(!is_null($description))$newPermission->description = $description;
        $newPermission->save();

        return response()->json(['level' => 'success','message' => '设置成功','data' => $newPermission]);
    }

    /**
     * 删除权限
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delPermissions(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        $thisPermission = Permission::whereId($id)->first();
        if(!$thisPermission)
            return response()->json(['level' => 'error','message' => '该角色不存在']);

        $thisPermission = DB::table('permissions')->where('id',$id)->delete();

        return response()->json(['level' => 'success','message' => '删除成功','data' => $thisPermission]);
    }
}
